package site.xuxingcan.autologin;

import android.accessibilityservice.AccessibilityService;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.FileInputStream;

public class MyAccessibilityService extends AccessibilityService {

    private WindowManager.LayoutParams wmParams;
    private WindowManager mWindowManager;
    private LinearLayout mFloatLayout;
    private View homeButton;
    private View loginButton;
    private Gson gson;

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWindowManager != null && mFloatLayout != null) {
            mWindowManager.removeView(mFloatLayout);
        }
    }

    @Override
    public void onInterrupt() {

    }

    private void createFloatView() {
        gson = new Gson();
        wmParams = new WindowManager.LayoutParams();
        //获取的是WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        //设置window type
        wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        //设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //调整悬浮窗显示的停靠位置为左侧置顶
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
        wmParams.x = mWindowManager.getDefaultDisplay().getWidth();
        wmParams.y = 150;

        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

		 /*// 设置悬浮窗口长宽数据
        wmParams.width = 200;
        wmParams.height = 80;*/

        //获取浮动窗口视图所在布局
        mFloatLayout = (LinearLayout) LayoutInflater.from(getApplication()).inflate(R.layout.float_layout, null);
        //添加mFloatLayout
        homeButton = mFloatLayout.findViewById(R.id.home);
        loginButton = mFloatLayout.findViewById(R.id.login);
        homeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
            }
        });
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String s = readText(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.txt");
                    Model model = gson.fromJson(s, Model.class);
                    if (model == null) {
                        Toast.makeText(getApplicationContext(), "文件未找到或格式错误！", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (!TextUtils.isEmpty(model.getQQ())) {
                        String qq = model.getQQ();
                        String qqPwd = model.getQQPwd();
                        if (!TextUtils.isEmpty(qqPwd)) {
                            android.content.ClipboardManager c = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                            AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                            AccessibilityNodeInfo qqNameEditText = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mobileqq:id/input").get(0).getChild(0);
                            c.setText(qq);
                            qqNameEditText.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            Thread.sleep(500);
                            qqNameEditText.performAction(AccessibilityNodeInfo.ACTION_PASTE);
                            Thread.sleep(500);
                            AccessibilityNodeInfo qqPwdEditText = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mobileqq:id/password").get(0);
                            c.setText(qqPwd);
                            qqPwdEditText.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            Thread.sleep(500);
                            qqPwdEditText.performAction(AccessibilityNodeInfo.ACTION_PASTE);
                            Thread.sleep(500);
                            AccessibilityNodeInfo qqLogin = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mobileqq:id/login").get(0);
                            qqLogin.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        }
                    } else if (!TextUtils.isEmpty(model.getPhone_line1number())) {

                    } else {
                        Toast.makeText(getApplicationContext(), "没有QQ或微信账号信息！", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        mWindowManager.addView(mFloatLayout, wmParams);
    }

    private String readText(String path) throws Exception {
//        FileInputStream inputStream = new FileInputStream(path);
//        byte[] bytes = new byte[1024];
//        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
//        while (inputStream.read(bytes) != -1) {
//            arrayOutputStream.write(bytes, 0, bytes.length);
//        }
//        inputStream.close();
//        arrayOutputStream.close();
//        return new String(arrayOutputStream.toByteArray(), "UTF-8");
        FileInputStream fin = new FileInputStream(path);
        int length = fin.available();
        byte[] buffer = new byte[length];
        fin.read(buffer);
        fin.close();
        return new String(buffer, "UTF-8");
    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        createFloatView();
    }
}
